package ua.com.myjava.francais;

import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.oauth2.OAuth2Auth;
import io.vertx.ext.auth.oauth2.OAuth2ClientOptions;
import io.vertx.ext.auth.oauth2.OAuth2FlowType;
import io.vertx.ext.web.Cookie;
import io.vertx.ext.web.RoutingContext;

public class FbLoginHandler implements Handler<RoutingContext> {
    private final OAuth2Auth oauth2;

    private FbLoginHandler(Vertx vertx) {
        OAuth2ClientOptions credentials = new OAuth2ClientOptions()
                .setClientID("200115490469809")
                .setClientSecret("3f4654f20a2dcf0e79e3926df87c4f2e")
                .setSite("https://www.facebook.com")
                .setAuthorizationPath("/dialog/oauth")
                .setTokenPath("https://graph.facebook.com/v2.8/oauth/access_token");


        // Initialize the OAuth2 Library
        oauth2 = OAuth2Auth.create(vertx, OAuth2FlowType.AUTH_CODE, credentials);
    }

    public static FbLoginHandler create(Vertx vertx) {
        return new FbLoginHandler(vertx);
    }


    @Override
    public void handle(RoutingContext event) {
        if (event.request().absoluteURI().contains("login-fb")) {
            // Authorization oauth2 URI
            String authorization_uri = oauth2.authorizeURL(new JsonObject()
                    .put("redirect_uri", "http://localhost:18080/callback-fb")
                    .put("scope", "public_profile,email"));

            // Redirect example using Vert.x
            event.response().putHeader("Location", authorization_uri)
                    .setStatusCode(302)
                    .end();
        } else {
            String code = event.request().getParam("code");
            oauth2.getToken(new JsonObject().put("code", code).put("redirect_uri", "http://localhost:18080/callback-fb"), res -> {
                if (res.failed()) {
                    event.response().putHeader("Location", "/login.html").setStatusCode(302).end();
                } else {
                    event.setUser(res.result());
                    event.addCookie(Cookie.cookie("login_success", "true"));
                    event.addCookie(Cookie.cookie("expires_at", String.valueOf(res.result().principal().getLong("expires_at"))));
                    event.response().putHeader("Location", "/").setStatusCode(302).end();
                }
            });
        }
    }
}
